package bar.dark.lee.stats;

import java.math.BigDecimal;
import java.util.Calendar;

import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class StatsActivity extends SuperActivity
{
	public static final String STATS_CATEGORY_FLAG = "stats_category_flag";
	public static final String STATS_MONTH_FLAG = "stats_month_flag";
	public static final String SELECT_YEAR = "stats_select_year";
	public static final String SELECT_MONTH = "stats_select_month";
	public static final String SELECT_CATEGORY = "stats_select_category";
	public static final String SELECT_MONEYKIND = "stats_select_moneykind";
	
	public static final int STATS_IN = 0;
	public static final int STATS_OUT = 1;
	public static final int STATS_MOVE = 2;
	public static final int STATS_BALANCE = 3;
	public static final int STATS_ASSET_MANAGER = 4;
	
	private DBSQLite sql;
	
	private View dangerView;
	private TextView dangerTextView;
	
	private View inCategoryButton;
	private View outCategoryButton;
	private View moveCategoryButton;
	private View assetButton;
	private View inMonthButton;
	private View outMonthButton;
	private View balenceMonthButton;
	private View assetMonthButton;
	
	private int year;
	private int month;
	private int date;
	
	private BigDecimal totalOutmoney;
	private BigDecimal totalInmoney;
	
	private BigDecimal totalMoney;
	
	private int avgCount;
	private int percent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setTitle("통계");
		
		setContentView(R.layout.stats_activity);
		
		setFindView();
		setOnclickListener();
		new ShowDialog().execute(0);
	}

	private void setFindView()
	{
		dangerView = findViewById(R.id.statsDangerView);
		dangerTextView = (TextView) findViewById(R.id.statsDangerTextView);
		
		inCategoryButton = findViewById(R.id.statsInCategoryButton);
		outCategoryButton = findViewById(R.id.statsOutCategoryButton);
		moveCategoryButton = findViewById(R.id.statsMoveCategoryButton);
		assetButton = findViewById(R.id.statsAssetButton);
		inMonthButton = findViewById(R.id.statsInMonthButton);
		outMonthButton = findViewById(R.id.statsOutMonthButton);
		balenceMonthButton = findViewById(R.id.statsBalanceMonthButton);
		assetMonthButton = findViewById(R.id.statsAssetMonthButton);
	}
	
	private void setOnclickListener()
	{
		inCategoryButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(StatsActivity.this, StatsCategoryActivity.class);
				intent.putExtra(STATS_CATEGORY_FLAG, STATS_IN);
				startActivity(intent);
			}
		});
		
		outCategoryButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(StatsActivity.this, StatsCategoryActivity.class);
				intent.putExtra(STATS_CATEGORY_FLAG, STATS_OUT);
				startActivity(intent);
			}
		});
		
		moveCategoryButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(StatsActivity.this, StatsCategoryActivity.class);
				intent.putExtra(STATS_CATEGORY_FLAG, STATS_MOVE);
				startActivity(intent);
			}
		});
		
		assetButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(StatsActivity.this, StatsAssetActivity.class);
				startActivity(intent);
			}
		});
		
		inMonthButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(StatsActivity.this, StatsMonthActivity.class);
				intent.putExtra(STATS_MONTH_FLAG, STATS_IN);
				startActivity(intent);
			}
		});
		
		outMonthButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(StatsActivity.this, StatsMonthActivity.class);
				intent.putExtra(STATS_MONTH_FLAG, STATS_OUT);
				startActivity(intent);
			}
		});
		
		balenceMonthButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(StatsActivity.this, StatsMonthActivity.class);
				intent.putExtra(STATS_MONTH_FLAG, STATS_BALANCE);
				startActivity(intent);
			}
		});
		
		assetMonthButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(StatsActivity.this, StatsMonthActivity.class);
				intent.putExtra(STATS_MONTH_FLAG, STATS_BALANCE);
				startActivity(intent);
			}
		});
	}
	
	private void setData()
	{
		Calendar cal = Calendar.getInstance();
		year = cal.get(Calendar.YEAR);
		month = cal.get(Calendar.MONTH);
		date = cal.get(Calendar.DAY_OF_MONTH);
		
		// 달 시작일 가져온다
    	SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	int startDate = Integer.parseInt(pref.getString(BDConstents.START_DATE, "1"));
    	
    	String inQuery = "";
    	String outQuery = "";
    	
    	String firstDate = "";
    	String lastDate = "";
    	
    	// 시작일이 1일이면 원래대로
    	if (startDate == 1) 
    	{
    		firstDate = BDUtil.getDateDB(year, month+1, 1);
    		lastDate = BDUtil.getDateDB(year, month+1, 31); 
    	}
    	else
    	{
    		if (month+1 == 1)
    		{
    			// 1월이면 
    			if (date < startDate)
    			{
    				// 저번달에 낑겨있으면
    				// 1월이면 작년 12월 시작일부터 올해 이번달 시작일전날까지
        			// 이달의 지출
    				firstDate = BDUtil.getDateDB(year-1, 12, startDate);
    				lastDate = BDUtil.getDateDB(year, 1, startDate-1);
    			}
    			else
    			{
    				// 새달이 시작됐으면
    				// 1월이면 1월 시작일부터 2월 시작일전날까지
        			// 이달의 지출
    				firstDate = BDUtil.getDateDB(year, 1, startDate);
    				lastDate = BDUtil.getDateDB(year, 2, startDate-1);
    			}    			
    		}
    		else if (month+1 == 12)
    		{
    			// 12월이면 
    			if (date < startDate)
    			{
    				// 저번달에 낑겨있으면
    				// 올해 11월 시작일부터 올해 12월 시작일전날까지
        			// 이달의 지출
    				firstDate = BDUtil.getDateDB(year, 11, startDate);
    				lastDate = BDUtil.getDateDB(year, 12, startDate-1);
    			}
    			else
    			{
    				// 새달이 시작됐으면
    				// 작년 12월 시작일부터 1월 시작일전날까지
        			// 이달의 지출
    				firstDate = BDUtil.getDateDB(year, 12, startDate);
    				lastDate = BDUtil.getDateDB(year+1, 1, startDate-1);
    			}
    		}
    		else
    		{
    			// 1월이 아니면
    			if (date < startDate)
    			{
    				// 전달에 낑겨있으면
    				// 이달의 지출
    				firstDate = BDUtil.getDateDB(year, month, startDate);
    				lastDate = BDUtil.getDateDB(year, month+1, startDate-1);
    			}
    			else
    			{
    				// 새달이 시작됐으면
    				// 이달의 지출
    				firstDate = BDUtil.getDateDB(year, month+1, startDate);
    				lastDate = BDUtil.getDateDB(year, month+2, startDate-1);
    			}
    		}
    	}
    	
    	inQuery = "SELECT inmoney FROM in_out WHERE inmoney not in ('0') and date >= " +
				firstDate + " and date <= " +
				lastDate;
		outQuery = "SELECT outmoney FROM in_out WHERE outmoney not in ('0') and date >= " +
				firstDate + " and date <= " +
				lastDate;
    	
		sql.selectMapTile(this, inQuery, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("inmoney");
				totalInmoney = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
//					totalInmoney += Integer.parseInt(c.getString(moneyIdx));
					totalInmoney = totalInmoney.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
			}
		});
		
		sql.selectMapTile(this, outQuery, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("outmoney");
				totalOutmoney = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
//					totalOutmoney += Integer.parseInt(c.getString(moneyIdx));
					totalOutmoney = totalOutmoney.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
			}
		});
	}

	private void setStatsData()
	{
		totalMoney = totalInmoney.subtract(totalOutmoney);
		
		if (totalMoney.compareTo(BigDecimal.ZERO) > 0)
		{
			avgCount = (int)(((double)Math.abs(totalMoney.doubleValue()) 
					/ (double)(totalInmoney.doubleValue())) * 100);
			percent = 50 + (avgCount/2);
		}
		else
		{
			avgCount = (int)(((double)Math.abs(totalMoney.doubleValue()) 
					/ (double)(totalOutmoney.doubleValue())) * 100);
			percent = 50 - (avgCount/2);
		}
		
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT);
		params.weight = percent;
		dangerView.setLayoutParams(params);
		
		if (percent >= 0 && percent < 21)
		{
			dangerTextView.setText("매우위험");
		}
		else if (percent >= 21 && percent < 41)
		{
			dangerTextView.setText("위험");
		}
		else if (percent >= 41 && percent < 61)
		{
			dangerTextView.setText("안전");
		}
		else if (percent >= 61 && percent < 81)
		{
			dangerTextView.setText("양호");
		}
		else if (percent >= 81 && percent < 101)
		{
			dangerTextView.setText("매우양호");
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(StatsActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				setData();
				return 0;
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == 0)
			{
				setStatsData();
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_STATS);
		startActivity(intent);
	}
}
